<!-- 物资设备采购策划表 -->
<template>
    <div>
      <a-card>
        <title-name title="重大技术方案表" />
        <a-button class="mt20 mb20" type="primary" @click="addRow" v-if="queryInfo.pageType !== 'detail'"> 增行 </a-button>
        <a-table :columns="columns" :data-source="data" bordered :pagination="false">
          <span slot="serial" slot-scope="text, record, index">{{ index + 1 }}</span>
          <!-- 重大方案名称 -->
          <span slot="name" slot-scope="text, record, index">
            <span v-if="queryInfo.pageType == 'detail'">{{ text }}</span>
            <EditableCell :required="true" v-else :key="index + '-name'" :text="text" @change="onCellChange(record, 'name', $event)" :maxLength="100"></EditableCell>
          </span>
          <!-- 方案内容 -->
          <span slot="planContent" slot-scope="text, record, index">
            <span v-if="queryInfo.pageType == 'detail'">{{ text }}</span>
            <EditableCell :required="true" v-else :key="index + '-planContent'" :text="text" @change="onCellChange(record, 'planContent', $event)" :maxLength="1000"></EditableCell>
          </span>
          <!-- 责任人 -->
          <span slot="principalId" slot-scope="text, record, index">
            <span v-if="queryInfo.pageType == 'detail'">{{ record.principal }}</span>
            <div v-else class="requiredFormItem">
              <SelectPerson :fetching="fetching" :key="index + '-principalId'" @changeEmployeeName="changeEmployeeName" :memberList="memberList" :record="record" bindKey="principalId"></SelectPerson>
            </div>
          </span>
          <!-- 计划编制时间 -->
          <span slot="planTime" slot-scope="text, record, index">
            <span v-if="queryInfo.pageType == 'detail'">{{ text }}</span>
            <EditableDate :required="true" v-else :key="index + '-planTime'" :text="text" @change="onCellChange(record, 'planTime', $event)"></EditableDate>
          </span>
          <span slot="operation" slot-scope="text, record">
            <template>
              <a-popconfirm title="请确认是否要删除？" @confirm="() => onDelete(record)">
                <a href="javascript:;">删除</a>
              </a-popconfirm>
            </template>
          </span>
        </a-table>
      </a-card>
    </div>
  </template>
  
  <script>
  import EditableCell from '../../../projectManagementPlanning/projectPlanningTaskList/detail/components/EditableCell'
  import EditableNumber from '../../../projectManagementPlanning/projectPlanningTaskList/detail/components/EditableNumber'
  import EditableDate from '../../../projectManagementPlanning/projectPlanningTaskList/detail/components/EditableDate'
  import { getOrganizeUserListQuick } from '@/api/commons'
  
  import SelectPerson from '../../../projectManagementPlanning/projectManagementPlanningComponents/components/ProjectDesignPlanningForm/SelectPerson'
  import { querySchemeMajorTechnicalPlanDetail, schemeSchemeMajorTechnicalPlanUpdateList } from '@/api/project/plannManagement/interpenetrationPlan.js'
  
  const DEFAULT_ROW = [
    {
      name: '',
      planContent: '',
      principal: '',
      principalId: '',
      planTime: '',
      guid: new Date().getTime()
    }
  ]
  
  const REQUEST_KEYS = [
    'name',
    'planContent',
    'principal',
    'principalId',
    'planTime',
  ]
  export default {
    name: 'ProcurementPlanning',
    data() {
      return {
        queryInfo: {
          id: '',
          pageType: ''
        },
        columns: [
          {
            title: '序号',
            width: 50,
            align: 'center',
            dataIndex: 'serial',
            scopedSlots: { customRender: 'serial' }
          },
          {
            title: '重大方案名称',
            width: 150,
            align: 'center',
            dataIndex: 'name',
            scopedSlots: { customRender: 'name' }
          },
          {
            title: '方案内容',
            align: 'center',
            dataIndex: 'planContent',
            scopedSlots: { customRender: 'planContent' }
          },
          {
            title: '责任人',
            width: 150,
            align: 'center',
            dataIndex: 'principalId',
            scopedSlots: { customRender: 'principalId' }
          },
          {
            title: '计划编制时间',
            width: 150,
            align: 'center',
            dataIndex: 'planTime',
            scopedSlots: { customRender: 'planTime' }
          },
          {
            title: '操作',
            align: 'center',
            fixed: 'right',
            width: 100,
            dataIndex: 'operation',
            scopedSlots: { customRender: 'operation' }
          }
        ],
        data: [],
        memberList: [], // 接收人
        fetching: false
      }
    },
  
    props: {
      spinning: Boolean,
      baseFormInfo: {
        type: Object,
        default: () => {}
      }
    },
  
    components: { EditableCell, EditableNumber, EditableDate, SelectPerson },
  
    computed: {},
  
    watch: {
      baseFormInfo: {
        handler(val) {
          if (val.projectId) {
            this.getImplees()
          }
        },
        immediate: true
      }
    },
  
    created() {
      const { id, pageType, version = '' } = this.$route.query
      /**
       * version 不存在 就是正常入口进来的。
       * 否则 就是在V1等弹窗进来的
       */
      this.queryInfo.id = id
      this.queryInfo.pageType = pageType
      this.queryInfo.version = version
      if (this.queryInfo.pageType === 'detail') {
        this.columns.pop()
      }
      this.queryPlanSubSelectDetail()
    },
  
    mounted() {},
  
    methods: {
      // 增行
      addRow() {
        const DEFAULT_ROW_ = JSON.parse(JSON.stringify(DEFAULT_ROW))
        this.data.push({ ...[...DEFAULT_ROW_][0], guid: this.getGuid() })
      },
      // 草稿
      TechnicalProposalSaveDrafts(formBase) {
        this.$emit('update:spinning', true)
        const query = {
          list: JSON.parse(JSON.stringify(this.data)),
          changed: this.queryInfo.pageType === 'change' ? true : false,
          schemeDetailId: this.queryInfo.id,
          status: 0,
          version: this.queryInfo.version
        }
        formBase.schemeDetailId = this.queryInfo.id
        formBase.status = 0
        this.$emit('updateBasicDetail', formBase)
        schemeSchemeMajorTechnicalPlanUpdateList(query)
          .then((res) => {
            this.$emit('update:spinning', false)
            this.$message.success('保存成功')
          })
          .catch(() => {
            this.$emit('update:spinning', false)
          })
      },
      // 提交
      TechnicalProposalSubmit(formBase) {
        let flag = true // 是否全部填写
        this.data.map((v) => {
          REQUEST_KEYS.map((k) => {
            if (v[k] === '' || v[k] == null || v[k] == undefined || (v[k] + '').replace(/\s*/g, '') == '') {
              flag = false
            }
          })
        })
        if (this.data.length === 0) {
          this.$warning({
            title: '提示',
            content: '请至少填写一行数据',
            okText: '确定'
          })
          return
        }
        if (!flag) {
          this.$warning({
            title: '提示',
            content: '请将数据填写完整',
            okText: '确定'
          })
          return
        } else {
          this.$confirm({
            title: '提交',
            content: '请确认是否要提交？',
            onOk: async () => {
              this.$emit('update:spinning', true)
              const query = {
                list: JSON.parse(JSON.stringify(this.data)),
                changed: this.queryInfo.pageType === 'change' ? true : false,
                schemeDetailId: this.queryInfo.id,
                status: 1,
                version: this.queryInfo.version
              }
              formBase.schemeDetailId = this.queryInfo.id
              formBase.status = 1
              this.$emit('updateBasicDetail', formBase)
              schemeSchemeMajorTechnicalPlanUpdateList(query)
                .then((res) => {
                  this.$emit('update:spinning', false)
                  this.$message.success('提交成功')
                  this.$emit('closePage');
                })
                .catch(() => {
                  this.$emit('update:spinning', false)
                })
            },
            onCancel: () => { this.$emit('update:spinning', false)}
          })
        }
      },
      getGuid() {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
          var r = (Math.random() * 16) | 0
          var v = c === 'x' ? r : (r & 0x3) | 0x8
          return v.toString(16)
        })
      },
      // 删除item
      onDelete(item) {
        let arr = JSON.parse(JSON.stringify(this.data))
        arr = arr
          .map((v) => {
            if (v.guid !== item.guid) {
              return v
            }
          })
          .filter((v) => v && v.guid)
        this.data = arr
      },
      // 更新item
      onCellChange(item, dataIndex, value) {
        this.data.map((v) => {
          if (v.guid === item.guid) {
            v[dataIndex] = value
          }
        })
      },
      // 获取接收人
      getImplees() {
        this.fetching = true
        getOrganizeUserListQuick({ projectId: this.baseFormInfo.projectId }).then((res) => {
          const obj = {}
          // 去掉重复以及employeeId为空的数据
          res.data = res.data.reduce(function (item, next) {
            obj[next.employeeId] || !next.employeeId ? '' : (obj[next.employeeId] = true && item.push(next))
            return item
          }, [])
          this.memberList = res.data
          this.fetching = false
        })
      },
      // 选择接收人
      changeEmployeeName({ guid, key, id, name, phone }) {
        this.data.map((v) => {
          if (v.guid === guid) {
            if (key == 'principalId') {
              v.principalId = id
              v.principal = name
            }
          }
        })
      },
      // 获取详情
      queryPlanSubSelectDetail() {
        this.$emit('update:spinning', true)
        const query = {
            schemeDetailId: this.queryInfo.id,
            latestData: true
        }
        if (this.queryInfo.version) {
            query.latestData = false
            query.version = this.queryInfo.version
        }
        querySchemeMajorTechnicalPlanDetail(query)
          .then((res) => {
            if (res.data && res.data.length) {
              res.data.map((v) => (v.guid = this.getGuid()))
              this.data = res.data
            } else {
              const DEFAULT_ROW_ = JSON.parse(JSON.stringify(DEFAULT_ROW))
              this.data = [...DEFAULT_ROW_]
            }
            this.$emit('update:spinning', false)
          })
          .catch(() => {
            this.$emit('update:spinning', false)
          })
      }
    }
  }
  </script>
  <style lang='less' scoped>
  </style>